package org.jeecgframework.web.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.model.json.Tree;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.web.service.SoftwareVersionServiceI;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.SendMessage;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;

import java.io.IOException;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import org.jeecgframework.core.util.ExceptionUtil;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 软件版本
 * @date 2018-02-10 10:54:24
 */
@Scope("prototype")
@Controller
@RequestMapping("/softwareVersionController")
public class SoftwareVersionController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(SoftwareVersionController.class);

    @Autowired
    private SoftwareVersionServiceI softwareVersionService;
    @Autowired
    private SystemService systemService;
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 软件版本列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "softwareVersion")
    public ModelAndView softwareVersion(HttpServletRequest request) {
        return new ModelAndView("com/zybk/softwareversion/softwareVersionList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(SoftwareVersionEntity softwareVersion, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(SoftwareVersionEntity.class, dataGrid);
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, softwareVersion, request.getParameterMap());
        try {
            //自定义追加查询条件
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        this.softwareVersionService.getDataGridReturn(cq, true);

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 软件版本新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(SoftwareVersionEntity softwareVersion, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(softwareVersion.getId())) {
            softwareVersion = softwareVersionService.getEntity(SoftwareVersionEntity.class, softwareVersion.getId());
            req.setAttribute("softwareVersionPage", softwareVersion);
        }
        return new ModelAndView("com/zybk/softwareversion/softwareVersion-add");
    }


    /**
     * 添加软件版本
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(SoftwareVersionEntity softwareVersion, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        boolean flag = true;
        try {
            String type = request.getParameter("type");
            String typeName = request.getParameter("typeName");
            String sql = "SELECT id from cbs_software_version v WHERE sofe_name = '" + softwareVersion.getSofeName() + "'";
            List<Map<String, Object>> softwareVersions = systemService.findForJdbc(sql);
            if (softwareVersions.size() > 0 && StringUtil.isNotEmpty(typeName)) {
                String[] str = typeName.split(",");
                for (String s : str) {
                    String sql1 = "SELECT id from cbs_software_version  WHERE zy_esitem_name like '%" + s + "%' and sofe_name='"+softwareVersion.getSofeName()+"'";
                    List<Map<String, Object>> maps = systemService.findForJdbc(sql1);
                    if (maps.size() > 0) {
                        flag = false;
                        break;
                    }
                }

                if (flag) {
                    softwareVersion.setZyEsitem(type);
                    softwareVersion.setZyEsitemName(typeName);
                    softwareVersion.setDate(new Date());
                    softwareVersionService.save(softwareVersion);

                    message = "软件版本添加成功";
                    systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
                    //启动线程发送消息
                    TSUser user = ResourceUtil.getSessionUserName();
                    addCbsSoftMessage(softwareVersion.getSofeName(),user.getId());
                } else {
                    j.setMsg(message);
                    j.setSuccess(false);
                    j.setMsg("添加机型中有与旧机型重合的机型，请核对后再添加！");
                }
            } else {
                message = "软件版本添加成功";
                softwareVersion.setZyEsitem(type);
                softwareVersion.setZyEsitemName(typeName);
                softwareVersion.setDate(new Date());
                softwareVersionService.save(softwareVersion);
                systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
                j.setMsg(message);

                //启动线程发送消息
                TSUser user = ResourceUtil.getSessionUserName();
                addCbsSoftMessage(softwareVersion.getSofeName(),user.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "软件版本添加失败";
            throw new BusinessException(e.getMessage());
        }
        return j;
    }

    public void appMessage(final SoftwareVersionEntity softwareVersion, final TSUser user){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                List<TSUser> user1 = systemService.getList(TSUser.class);
                CbsAppMessageEntity appMessage = new CbsAppMessageEntity();
                String content = "中影巴可软件版本 "+softwareVersion.getSofeName()+" 更新新版本，版本号"+softwareVersion.getVersion()+"。请点击首页的【软件版本】，查看详情。";
                appMessage.setContent ( content );
                appMessage.setSender ( user.getId () );
                for (TSUser tsUser : user1) {
                    if(tsUser.getStatus().equals(Globals.User_Normal)){  // 18/5/17新增查询条件  正常登陆的用户
                        appMessage.setReciver ( tsUser.getId () );
                        appMessage.setState ( StaticValue.DIC_APP_MESSAGE_STATE_UNREAD );
                        appMessage.setCreateBy(user.getUserName());
                        appMessage.setCreateDate(new Date());
                        appMessage.setCreateName(user.getRealName());
                        systemService.save ( appMessage );
                        systemService.addLog ( "新增APP消息,接受方:" + tsUser.getId () + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL );
                    }
                }
            }
        },10);

    }

    public void addCbsSoftMessage(final String softname, final String userId) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                /*软件版本推送内容*/
                List<TSUser> user1 = systemService.getList(TSUser.class);
                for (TSUser tsUser : user1) {
                    if(tsUser.getStatus().equals(Globals.User_Normal)){  // 18/5/17新增查询条件  正常登陆的用户
                        //查询未读表中是否有该软件名称的消息，如果有，将该消息变为 未读
                        String hql="from CbsSoftMessageEntity WHERE reciver='"+tsUser.getId()+"' and content like '"+softname+"'";
                        List<CbsSoftMessageEntity> cbsSoftMessages = systemService.findByQueryString(hql);
                        if(cbsSoftMessages.size()>0){
                            for (CbsSoftMessageEntity cbsSoftMessage : cbsSoftMessages) {
                                cbsSoftMessage.setState(StaticValue.softNo);
                                systemService.saveOrUpdate(cbsSoftMessage);
                            }
                        }else{
                            CbsSoftMessageEntity appSoftMessage = new CbsSoftMessageEntity();
                            appSoftMessage.setSender(userId);
                            appSoftMessage.setReciver(tsUser.getId());
                            appSoftMessage.setContent(softname); //版本信息id
                            appSoftMessage.setState(StaticValue.softNo);
                            systemService.save(appSoftMessage);
                        }
                        systemService.addLog ( "新增软件版本消息,接受方:" + tsUser.getId () , Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL );
                    }
                }
            }
        },10);
    }

    //获取所有的CSA角色
    /**
     * 软件版本编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(SoftwareVersionEntity softwareVersion, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(softwareVersion.getId())) {
            softwareVersion = softwareVersionService.getEntity(SoftwareVersionEntity.class, softwareVersion.getId());
            req.setAttribute("softwareVersionPage", softwareVersion);
        }
        return new ModelAndView("com/zybk/softwareversion/softwareVersion-update");
    }

    /**
     * 更新软件版本
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(SoftwareVersionEntity softwareVersion, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        //message = "软件版本更新成功";
        boolean flag = true;
        SoftwareVersionEntity t = softwareVersionService.get(SoftwareVersionEntity.class, softwareVersion.getId());
        try {
            String zyEsitem = request.getParameter("zyEsitem");
            String zyEsitemName = request.getParameter("zyEsitemName");
            String sql = "SELECT id from cbs_software_version v WHERE sofe_name = '" + softwareVersion.getSofeName() + "'";
            List<Map<String, Object>> softwareVersionList = systemService.findForJdbc(sql);
            if (softwareVersionList.size() > 0 && StringUtil.isNotEmpty(zyEsitemName)) {
                String[] str = zyEsitemName.split(",");
                for (String s : str) {
                    String sql1 = "SELECT id from cbs_software_version  WHERE zy_Esitem_Name like '%" + s + "%' and sofe_name='"+softwareVersion.getSofeName()+"' and id != '" + softwareVersion.getId() + "'";
                    List<Map<String, Object>> maps = systemService.findForJdbc(sql1);
                    if (maps.size() > 0 && !zyEsitemName.equals(t.getZyEsitemName())) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    t.setState("2");
                    t.setDate(new Date());
                    softwareVersionService.saveOrUpdate(t);
                    SoftwareVersionEntity softwareVersions = new SoftwareVersionEntity();
                    softwareVersions.setSofeName(softwareVersion.getSofeName());
                    softwareVersions.setState("1");
                    softwareVersions.setZyEsitem(softwareVersion.getZyEsitem());
                    softwareVersions.setZyEsitemName(softwareVersion.getZyEsitemName());
                    softwareVersions.setCreateName(softwareVersion.getCreateName());
                    softwareVersions.setVersion(softwareVersion.getVersion());
                    softwareVersions.setVersionExplain(softwareVersion.getVersionExplain());
                    softwareVersions.setDate(new Date());
                    softwareVersionService.saveOrUpdate(softwareVersions);

                    message = "软件版本更新成功";
                    j.setMsg(message);

                    /*5.向APP发送中影巴可软件版本更新通知，并在“软件版本”图标上显示红点*/
                    //启动线程发送消息
                    TSUser user = ResourceUtil.getSessionUserName();
                    addCbsSoftMessage(softwareVersions.getSofeName(),user.getId());
                    /*APP消息*/
                    appMessage(softwareVersion,user);

                } else {
                    j.setMsg(message);
                    j.setSuccess(false);
                    j.setMsg("添加机型中有与旧机型重合的机型，请核对后再添加！");
                }

            } else {
                t.setState("2");
                softwareVersionService.saveOrUpdate(t);
                SoftwareVersionEntity softwareVersions = new SoftwareVersionEntity();
                softwareVersions.setSofeName(softwareVersion.getSofeName());
                softwareVersions.setState("1");
                softwareVersions.setZyEsitem(softwareVersion.getZyEsitem());
                softwareVersions.setZyEsitemName(softwareVersion.getZyEsitemName());
                softwareVersions.setCreateName(softwareVersion.getCreateName());
                softwareVersions.setVersion(softwareVersion.getVersion());
                softwareVersions.setVersionExplain(softwareVersion.getVersionExplain());
                softwareVersionService.saveOrUpdate(softwareVersions);

                message = "软件版本更新成功";
                j.setMsg(message);

                /*软件版本推送内容*/
                TSUser user = ResourceUtil.getSessionUserName();
                //启动线程发送消息
                addCbsSoftMessage(softwareVersions.getSofeName(),user.getId());


                /*APP消息*/
                appMessage(softwareVersion,user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "软件版本更新失败";
            throw new BusinessException(e.getMessage());
        }
        return j;
    }


    /**
     * 删除软件版本
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(SoftwareVersionEntity softwareVersion, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        softwareVersion = systemService.getEntity(SoftwareVersionEntity.class, softwareVersion.getId());
        message = "软件版本删除成功";
        try {
            softwareVersionService.delete(softwareVersion);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "软件版本删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除软件版本
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "软件版本删除成功";
        try {
            for (String id : ids.split(",")) {
                SoftwareVersionEntity softwareVersion = systemService.getEntity(SoftwareVersionEntity.class,
                        id
                );
                softwareVersionService.delete(softwareVersion);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "软件版本删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView("com/zybk/softwareversion/softwareVersionUpload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public void exportXls(HttpServletRequest request, HttpServletResponse response) {
        softwareVersionService.exportXls(request, response);
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(SoftwareVersionEntity softwareVersion, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(TemplateExcelConstants.FILE_NAME, "软件版本");
        modelMap.put(TemplateExcelConstants.PARAMS, new TemplateExportParams("Excel模板地址"));
        modelMap.put(TemplateExcelConstants.MAP_DATA, null);
        modelMap.put(TemplateExcelConstants.CLASS, SoftwareVersionEntity.class);
        modelMap.put(TemplateExcelConstants.LIST_DATA, null);
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<SoftwareVersionEntity> listSoftwareVersionEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(), SoftwareVersionEntity.class, params);
                for (SoftwareVersionEntity softwareVersion : listSoftwareVersionEntitys) {
                    softwareVersionService.save(softwareVersion);
                }
                j.setMsg("文件导入成功！");
            } catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(ExceptionUtil.getExceptionMessage(e));
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

    @RequestMapping(params = "dataGridOfChooseEquipmentType")
    @ResponseBody
    public List<Tree> dataGridOfChooseEquipmentType(ZyEquipmentTypeEntity zyEquipmentTypeEntity, HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
        CriteriaQuery cq;
        List<Tree> treeGrids = new ArrayList<Tree>();
        cq = new CriteriaQuery(ZyEquipmentTypeEntity.class);
        //cq.notEq("typeDesc","设备");
        if (treegrid.getId() != null) {
            cq.eq("equipmentType.id", treegrid.getId());
        } else if (treegrid.getId() == null) {
             //cq.isNull("equipmentType.id");
            cq.eq("equipmentType.id", "402883f3545bca4101545be730e0000b");
        }
        cq.add();
        List<ZyEquipmentTypeEntity> ZyEquipmentTypeList = systemService.getListByCriteriaQuery(cq, false);
        /*TreeGridModel treeGridModel = new TreeGridModel();
        treeGridModel.setIdField("id");
		treeGridModel.setTextField("typeDesc");
		treeGridModel.setParentId("equipmentType_id");
		treeGridModel.setParentText("equipmentType_typeDesc");
		treeGridModel.setSrc("");
		treeGridModel.setChildList("childEquipmentTypes");
		treeGrids = systemService.treegrid(ZyEquipmentTypeList, treeGridModel);*/
        Tree t = new Tree("0", "放映机");
        assembleTree(t, ZyEquipmentTypeList);
        List<Tree> treeList = new ArrayList<>();
        treeList.add(t);
        return treeList;
    }

    public void assembleTree(Tree tree, List<ZyEquipmentTypeEntity> types) {
        Collections.sort(types, new Comparator<ZyEquipmentTypeEntity>() {
            @Override
            public int compare(ZyEquipmentTypeEntity o1, ZyEquipmentTypeEntity o2) {
                if (null == o1.getEquipmentType()) {
                    return -1;
                }
                if (null == o2.getEquipmentType()) {
                    return 1;
                }
                return 2;
            }
        });
        if (null == tree) {
            tree = new Tree();
            tree.setId("0");
            tree.setText("root");
        } else {
            for (ZyEquipmentTypeEntity type : types) {
                Tree t = new Tree(type.getId(), type.getTypeDesc());
                tree.getChildren().add(t);
                if (type.getChildEquipmentTypes().size() > 0) {
                    assembleTree(t, type.getChildEquipmentTypes());
                }
            }
        }
    }

    @RequestMapping(params = "goChooseEquipmentTypeCheckbox")
    public ModelAndView goChooseEquipmentTypeCheckbox(HttpServletRequest request) {
        return new ModelAndView("com/zybk/softwareversion/zyChooseEquipmentTypeForEsItemCheckBox");
    }

    /**
     * 获取软件版本list
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "goAppSoftwareList")
    public AjaxJson goAppSoftwareList(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        TSUser user = ResourceUtil.getSessionUserName();
        String s = "SELECT id,sofe_name AS sofename, max(DATE_FORMAT(create_date,'%Y-%m-%d  %H:%i:%s')) as date FROM cbs_software_version WHERE state !=2 GROUP BY sofe_name";
        List<Map<String, Object>> list = systemService.findForJdbc(s);
        if(list.size()>0){
            for (Map<String, Object> map : list) {
                if(StringUtil.isNotEmpty(map.get("sofename"))){
                    String sql="SELECT id from cbs_soft_message WHERE reciver='"+user.getId()+"' and state='"+StaticValue.softNo+"' and content like '"+map.get("sofename")+"'";
                    List<Map<String, Object>> sqllist = systemService.findForJdbc(sql);
                    if(sqllist.size()>0){
                        map.put("statusyd","0");
                    }
                 }
            }
        }
        ajaxJson.setObj(list);
        return ajaxJson;
    }

    /**
     * APP查看软件版本信息
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "viewAppSoft")
    public AjaxJson viewAppSoft(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = request.getParameter("id");
        String bussoftname = request.getParameter("bussoftname");
        if (StringUtil.isNotEmpty(id)&&StringUtil.isNotEmpty(bussoftname)) {
            TSUser user = ResourceUtil.getSessionUserName();
            //修改状态为已读
            String d = "UPDATE `cbs_soft_message` set state='"+StaticValue.softYes+"' where content like '" + bussoftname + "' and reciver='"+user.getId()+"'";
            systemService.updateBySqlString(d);
            String s = "SELECT id AS id, zy_esitem_name AS zyesitemname, version, create_date AS date, version_explain AS versionexplain FROM cbs_software_version WHERE sofe_name like '" + bussoftname + "' and state = '1'";
            List<Map<String, Object>> list = systemService.findForJdbc(s);
            ajaxJson.setObj(list);
        }
        return ajaxJson;
    }

    /**
     * APP 异步查询是否有未读的软件版本
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "queryAppSoftStatusYoN")
    public AjaxJson queryAppSoftStatusYoN(){
        AjaxJson ajaxJson = new AjaxJson();
        TSUser user = ResourceUtil.getSessionUserName();
        String sql="SELECT COUNT(*) from cbs_soft_message WHERE reciver='"+user.getId()+"' and state='"+StaticValue.softNo+"' ";
        List<Map<String, Object>> list = systemService.findForJdbc(sql);
        if(list.size()>0){
            ajaxJson.setObj(list.get(0).get("COUNT(*)"));
        }else{
            ajaxJson.setObj("0");
        }
        return ajaxJson;
    }

}
